package com.ccteam.fluidmusic.ui.search

import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentHomeSearchBinding
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.utils.hideKeyboard
import com.ccteam.fluidmusic.ui.playlist.select.AddOnlineMediaFragment.Companion.TYPE_SEARCH
import com.google.android.material.chip.Chip
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/3/16
 *
 * 首页搜索总界面
 */
@AndroidEntryPoint
class HomeSearchFragment: Fragment() {

    private var _binding: FragmentHomeSearchBinding? = null
    private val binding: FragmentHomeSearchBinding get() = _binding!!

    private val homeSearchViewModel by viewModels<HomeSearchViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentHomeSearchBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        binding.searchToolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        homeSearchViewModel.shouldShowResult.observe(viewLifecycleOwner, {
            showHideResult(it)
        })

        binding.editSearch.setOnFocusChangeListener { _, hasFocus ->
            if(hasFocus){
                homeSearchViewModel.showResult(!hasFocus)
            }
        }

        homeSearchViewModel.searchKey.observe(viewLifecycleOwner, {
            binding.viewpagerSearchResult.adapter = ResultViewPagerAdapter(it,this)
            TabLayoutMediator(binding.tabSearchResult, binding.viewpagerSearchResult) { tab, position ->
                when(position){
                    0 -> tab.text = getString(R.string.now_playing_tab_music)
                    1 -> tab.text = getString(R.string.online_music_album_type)
                    2 -> tab.text = getString(R.string.online_music_artist_type)
                    3 -> tab.text = getString(R.string.online_music_playlistSheet_type)
                }
            }.attach()
        })

        binding.editSearch.setOnKeyListener { _, keyCode, event ->
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP){
                searchKey(binding.editSearch.text.toString())

                hideKeyboard()
                // 确定搜索内容后，将搜索记录存储到DataStore中
                homeSearchViewModel.editCurrentSearchContent()
                return@setOnKeyListener true
            }
            // 没有进行处理则返回false让Navigation进行回退处理
            return@setOnKeyListener false
        }

        homeSearchViewModel.currentSearchList.observe(viewLifecycleOwner, {
            // 展示最近搜索内容
            updateRecentSearch(it)
        })

    }

    /**
     * 搜索相应内容
     * 会展示搜索结果界面以及清楚聚焦等操作
     */
    private fun searchKey(key: String){
        homeSearchViewModel.showResult(true)
        binding.editSearch.clearFocus()

        homeSearchViewModel.setNewSearchKey(key)
    }

    /**
     * 更新最近搜索的Chip内容
     */
    private fun updateRecentSearch(searchKeys: List<String>) = with(binding){
        chipRecentSearch.removeAllViews()
        searchKeys.forEach {
            val chip = layoutInflater.inflate(R.layout.recent_search_item,
                chipRecentSearch,false) as Chip
            chip.text = it
            chip.isCheckable = false
            // 设置点击事件
            chip.setOnClickListener {
                hideKeyboard()
                searchKey(chip.text.toString())
                binding.editSearch.setText(chip.text.toString())
            }
            binding.chipRecentSearch.addView(chip)
        }
    }

    private fun showHideResult(showResult: Boolean) = with(binding){
//        if(!showResult){
//            editSearch.requestFocus()
//        }
        groupSearchResult.isVisible = showResult
        groupSearchWelcome.isVisible = !showResult
    }

    class ResultViewPagerAdapter(
        private val searchKey: String,
        fragment: Fragment): FragmentStateAdapter(fragment){
        override fun getItemCount(): Int = 4

        override fun createFragment(position: Int): Fragment {
            return when(position){
                0 -> SearchMusicResultFragment.newInstance(searchKey, TYPE_SEARCH)
                1 -> SearchAlbumResultFragment.newInstance(searchKey, TYPE_SEARCH)
                2 -> HomeSearchArtistResultFragment.newInstance(searchKey)
                3 -> SearchPlaylistResultFragment.newInstance(searchKey, TYPE_SEARCH)
                else -> throw IllegalArgumentException("错误的布局参数")
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

const val SEARCH_KEY = "searchKey"